"""
修复缺失字段的迁移脚本
"""
from sqlalchemy import create_engine, text
from config import settings

def fix_missing_fields():
    """修复缺失的字段"""
    # 创建数据库引擎
    engine = create_engine(settings.database_url)
    
    with engine.begin() as conn:
        try:
            # 为email_configs表添加use_ssl和use_tls字段
            print("正在为email_configs表添加use_ssl字段...")
            conn.execute(text("ALTER TABLE email_configs ADD COLUMN use_ssl BOOLEAN NOT NULL DEFAULT FALSE COMMENT '是否使用SSL'"))
            print("✅ use_ssl字段添加成功")
            
            print("正在为email_configs表添加use_tls字段...")
            conn.execute(text("ALTER TABLE email_configs ADD COLUMN use_tls BOOLEAN NOT NULL DEFAULT FALSE COMMENT '是否使用TLS'"))
            print("✅ use_tls字段添加成功")
            
            # 为data_sources表添加description字段
            print("正在为data_sources表添加description字段...")
            conn.execute(text("ALTER TABLE data_sources ADD COLUMN description TEXT NULL COMMENT '数据源描述'"))
            print("✅ description字段添加成功")
            
            print("✅ 所有缺失字段修复完成")
            
        except Exception as e:
            print(f"修复字段失败: {e}")
            # 检查字段是否已存在
            try:
                # 检查email_configs表的字段
                result = conn.execute(text("SHOW COLUMNS FROM email_configs LIKE 'use_ssl'"))
                if result.fetchone():
                    print("ℹ️ use_ssl字段已存在")
                
                result = conn.execute(text("SHOW COLUMNS FROM email_configs LIKE 'use_tls'"))
                if result.fetchone():
                    print("ℹ️ use_tls字段已存在")
                
                # 检查data_sources表的字段
                result = conn.execute(text("SHOW COLUMNS FROM data_sources LIKE 'description'"))
                if result.fetchone():
                    print("ℹ️ description字段已存在")
                    
            except Exception as check_error:
                print(f"检查字段失败: {check_error}")

if __name__ == "__main__":
    fix_missing_fields()
